package com.wzl.Day23;

import java.util.concurrent.BlockingDeque;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingDeque;

public class ByBlockingQueue {
    public static void main(String[] args) {
        ByBlockingQueue byBlockingQueue = new ByBlockingQueue();
        BlockingDeque<Product> queue = new LinkedBlockingDeque<>();

        ExecutorService executorService = Executors.newCachedThreadPool();

        Producer p1 = new Producer("张三",queue);
        Producer p2 = new Producer("李四",queue);

        Consumer c1 = new Consumer("王五",queue);
        Consumer c2 = new Consumer("赵六",queue);
        Consumer c3 = new Consumer("田七",queue);

        executorService.submit(p1);
        executorService.submit(p2);
        executorService.submit(c1);
        executorService.submit(c2);
        executorService.submit(c3);
    }

    /*
    产品类
 */
    static class Product{
        private int id;

        public Product(int id){
            this.id = id;
        }

        public String toString(){
            return "产品"+this.id;
        }
    }


    /*
        生产者
     */
    static class Producer implements Runnable{
        private String name;
        private final BlockingDeque<Product> storage;

        public Producer(String name,BlockingDeque<Product> storage) {
            this.name = name;
            this.storage = storage;
        }

        @Override
        public void run() {
            try {
                for (int i = 0; i < 100; i++) {
                    Product product = new Product((int) (Math.random()*999));
                    System.out.println(name+"准备生产（"+product.toString()+"）");
                    storage.put(product);
                    System.out.println(name+"已经生产（"+product.toString()+"）");
                    System.out.println("=========================================");
                    Thread.sleep(5000);
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    /*
        消费者
     */
    static class Consumer implements Runnable{
        private String name;
        private BlockingDeque storage;

        public Consumer(String name, BlockingDeque storage){
            this.name = name;
            this.storage = storage;
        }

        @Override
        public void run() {
            for (int i = 0; i < 100; i++) {
                try {
                    System.out.println(name+"准备消费产品");
                    Product product = (Product) storage.take();
                    System.out.println(name+"已经消费（"+product.toString()+"）");
                    System.out.println("=========================================");
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
